using Microsoft.AspNetCore.Mvc;
using Microsoft.Playwright;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync();

builder.Services.AddSingleton<IPlaywright>((sp) => playwright);
builder.Services.AddSingleton((sp) => browser);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapPost("/Convert", async ([FromServices]IBrowser b, ConvertDto dto) =>
{

    IPage page = await b.NewPageAsync();
    await page.SetContentAsync(dto.Html);
    byte[] fileContents = await page.PdfAsync(new PagePdfOptions
    {
        DisplayHeaderFooter = true,
        Format = "A4",
        Margin = new Margin
        {
            Bottom = "1.27cm",
            Top = "1.27cm",
            Left = "1.27cm",
            Right = "1.27cm"
        },
        HeaderTemplate = dto.Header,
        FooterTemplate = dto.Footer
    });
    await page.CloseAsync();
    return Results.File(fileContents, "application/pdf");
})
.WithName("ConvertToPdf")
.WithOpenApi();

app.Run();

public record ConvertDto(string Html, string? Header, string? Footer);